<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudentSemestersService
{
    // 列表
        public static function index($data)
    {
        // 检查 category_id 是否存在
        if (!isset($data['category_id'])) {
            return ['code' => 400, 'msg' => 'Missing category_id', 'state' => 'Error', 'data' => null];
        }

        // 设置默认分页大小并限制最大值
        $limit = isset($data['limit']) ? (int)$data['limit'] : 10;
        $limit = max(1, min(100, $limit)); // 限制 limit 在 1~100 之间

        try {
            // 分页查询
            $studio = \app\admin\model\StudentSemester::where(['category_id' => $data['category_id']])
                ->field('semester_id,semester_name,semester_rule,total_lessons')
                ->order('semester_id', 'desc')
                ->paginate($limit);

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\Exception $e) {
            // 异常捕获，防止程序崩溃并隐藏敏感信息
            return ['code' => 500, 'msg' => 'Internal Server Error', 'state' => 'Error', 'data' => null];
        }
    }



    // 保存
    public static function save($data)
    {
        // 验证规则
        $validate = new Validate([
            'category_id' => 'require',
            'semester_name' => 'require',
            'semester_rule' => 'require',
            'total_lessons' => 'require',
        ], [
            'category_id.require' => 'CategoryId is not empty',
            'semester_name.require' => 'Semester Name is not empty',
            'semester_rule.require' => 'Semester Rule is not empty',
            'total_lessons.require' => 'Total Lessons is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            if(isset($data['semester_id']) && $data['semester_id']){
                $validate = new Validate([
                    'semester_id' => 'require',
                ], [
                    'semester_id.require' => 'SemesterId is not empty',
                ]);

                if (!$validate->check($data)) {
                    return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
                }
                $result  = \app\admin\model\StudentSemester::update($data);
            }else{
                $result = \app\admin\model\StudentSemester::create($data);
            }
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code'=>400, 'msg'=>'Database error: ' . $e->getMessage(), 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字

        if (empty($data['semester_id']) || !is_numeric($data['semester_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\StudentSemester::destroy($data['semester_id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 下拉查询
    public static function select($data)
    {
        // 校验 category_id 是否存在且合法
        if (!isset($data['category_id']) || empty($data['category_id'])) {
            return ['code' => 400, 'msg' => 'Missing or invalid category_id', 'state' => 'Error', 'data' => []];
        }

        try {
            $studio = \app\admin\model\StudentSemester::where([
                'category_id' => $data['category_id']
            ])
            ->field('semester_id,semester_name,semester_rule,total_lessons')
            ->order('semester_id', 'desc')
            ->select();
        } catch (\Exception $e) {
            // 记录日志（可选）
            // Log::error("Database error: " . $e->getMessage());

            return ['code' => 500, 'msg' => 'Database error occurred', 'state' => 'Error', 'data' => []];
        }

        return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
    }



}
